define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template'], function ($, undefined, Backend, Table, Form, Template) {

    var Controller = {
        index: function () {
            $(".btn-add").data("area",["100%","100%"]);
            $(".btn-edit").data("area",["100%","100%"]);
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'cms/archives/index',
                    add_url: 'cms/archives/add',
                    edit_url: 'cms/archives/edit',
                    del_url: 'cms/archives/del',
                    multi_url: 'cms/archives/multi',
                    dragsort_url: '',
                    table: 'cms_archives',
                }
            });

            var table = $("#table");

            //在表格内容渲染完成后回调的事件
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-editone").data("area",["100%","100%"]);
                //当为新选项卡中打开时
                if (Config.cms.archiveseditmode == 'addtabs') {
                    $(".btn-editone", this)
                        .off("click")
                        .removeClass("btn-editone")
                        .addClass("btn-addtabs")
                        .prop("title", __('Edit'));
                }
            });
            //当双击单元格时
            table.on('dbl-click-row.bs.table', function (e, row, element, field) {
                $(".btn-addtabs", element).trigger("click");
            });
            // var admin={43:'吴海月',10:'李星',12:'陈夏茵',291:'张琦',167:'郭纯慧',1:'CaAdmin',2:'黄志阳',5:'吴晓兴',26:'李芳',27:'陈聪',28:'罗少君',30:'宋文倩',31:'APP部公用号',34:'浙江高考早知道',41:"叶淑银",42:'张爱娟',140:'陈倩',13:'郑滟灵',271:'林晓雯',282:'谢慧',283:'彭蓉',25:'阮秋'};

            var content={1: "全国", 2: "北京", 3: "福建", 4: "浙江", 5: "河南", 6: "安徽", 7: "上海", 8: "江苏", 9: "山东", 10: "江西", 11: "重庆", 12: "湖南", 13: "湖北", 14: "广东", 15: "广西", 16: "贵州", 17: "海南", 18: "四川", 19: "云南", 20: "陕西", 21: "甘肃", 22: "宁夏", 23: "青海", 24: "新疆", 25: "西藏", 26: "天津", 27: "黑龙江", 28: "吉林", 29: "辽宁", 30: "河北", 31: "山西", 32: "内蒙古"};
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh DESC,publishtime DESC',
                pageSize:15,
                searchFormVisible: Fast.api.query("model_id") ? true : false,
                    columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), sortable: true},
                        {
                            field: 'user_id',
                            title: __('User_id'),
                            visible: false,
                            addclass: 'selectpage',
                            extend: 'data-source="user/user/index" data-field="nickname"',
                            operate: '=',
                            formatter: Table.api.formatter.search
                        },
                        {
                            field: 'admin_id',
                            title: __('Admin_id'),
                            visible: false,
                            addclass: 'selectpage',
                            extend: 'data-source="auth/admin/selectpage?flag=1" data-field="nickname"',
                            operate: '=',
                            formatter: Table.api.formatter.search
                        },
                        {
                            field: 'channel_id',
                            title: __('Channel_id'),
                            visible: false,
                            addclass: 'selectpage',
                            extend: 'data-source="cms/channel/index" data-field="name"',
                            operate: 'in',
                            formatter: Table.api.formatter.search
                        },
                        {
                            field: 'channel_ids',
                            title: __('Channel_ids'),
                            visible: false,
                            addclass: 'selectpage',
                            extend: 'data-source="cms/channel/index" data-field="name"',
                            operate: 'find_in_set',
                            formatter: Table.api.formatter.search
                        },
                        {
                            field: 'name',
                            title: __('Channel'),
                            operate: false,
                            formatter: function (value, row, index) {
                                return '<a href="javascript:;" class="searchit" data-field="channel_id" data-value="' + row.channel_id + '">' + value + '</a>';
                            }
                        },
                        // {field: 'admin_id', title: __('发布管理员'),
                        //     searchList : admin, formatter : Table.api.formatter.label},
                        {
                            field: 'nickname',
                            title: __('发布人')
                        ,operate: false
                        },
                        {
                            field: 'model_id',operate: false, title: __('Model'), visible: false, align: 'left', addclass: "selectpage", extend: "data-source='cms/modelx/index' data-field='name'"
                        },
                        // {
                        //     field: 'title', title: __('Title'), align: 'left', customField: 'flag', formatter: function (value, row, index) {
                        //         return '<div class="archives-title"><a href="' +(row.ago_url?row.ago_url:row.url) + '" target="_blank"><span style="color:' + (row.style_color ? row.style_color : 'inherit') + ';font-weight:' + (row.style_bold ? 'bold' : 'normal') + '">' + value + '</span></a></div>' +
                        //             '<div class="archives-label">' + Table.api.formatter.flag.call(this, row['flag'], row, index) + '</div>';
                        //     }
                        // },
                        {field: 'title', title: __('Title'),operate: 'like',  align: 'left', customField: 'flag',formatter: function (value, row, index) {
                                return '<div class="archives-title"><a href="http://admin.gkzzd.cn/cms/a/'+row.id+'.html"  " target="_blank">'+row.title+'</a></div>' ;
                            }
                        },
                        {
                            field: 'province',
                            title: __('省份'),
                            // addclass: 'selectpage',
                            operate: 'find_in_set',
                            formatter : Controller.api.formatter.content,
                            extend : content,
                            searchList : content,
                        },
                        {field: 'year', title: __('年份'),operate: '=',},

                        {field: 'flag', title: __('Flag'), operate: '=', visible: false, searchList: Config.flagList, formatter: Table.api.formatter.flag},
                        {field: 'image', title: __('Image'), operate: false, visible: false,events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'views',visible: false, title: __('Views'), operate: 'BETWEEN', sortable: true,operate:false},
                        {field: 'comments',visible: false, title: __('Comments'), operate: 'BETWEEN', sortable: true,operate:false},
                        {field: 'weigh', title: __('Weigh'), operate: false, sortable: true},
                        {field: 'source', title: __('来源'),visible: false, operate: false, sortable: false},
                        {
                            field: 'createtime',
                            title: __('Createtime'),
                            visible: false,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime,
                            autocomplete: false
                        },
                        {
                            field: 'updatetime',
                            title: __('Updatetime'),
                            visible: false,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime,
                            autocomplete: false
                        },
                        {
                            field: 'publishtime',
                            title: __('Publishtime'),
                            sortable: true,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime,
                            datetimeFormat: "YYYY-MM-DD",
                            autocomplete: false
                        },
                        {field: 'status', title: __('Status'), searchList: {"normal": __('Status normal'), "hidden": __('Status hidden'), "rejected": __('Status rejected'), "pulloff": __('Status pulloff')}, formatter: Table.api.formatter.status},

                        {
                            field: 'school_province',
                            title: __('院校省份'),
                            visible: true,
                            operate: '=',
                            searchList: {"北京": __('北京'), "福建": __('福建'), "浙江": __('浙江'), "河南": __('河南'), "安徽": __('安徽'), "上海": __('上海'), "江苏": __('江苏'), "山东": __('山东'), "江西": __('江西'), "重庆": __('重庆'), "湖南": __('湖南'), "湖北": __('湖北'), "广东": __('广东'), "广西": __('广西'), "贵州": __('贵州'), "海南": __('海南'), "四川": __('四川'), "云南": __('云南'), "陕西": __('陕西'), "甘肃": __('甘肃'), "宁夏": __('宁夏'), "青海": __('青海'), "新疆": __('新疆'), "西藏": __('西藏'), "天津": __('天津'), "黑龙江": __('黑龙江'), "吉林": __('吉林'), "辽宁": __('辽宁'), "河北": __('河北'), "山西": __('山西'), "内蒙古": __('内蒙古')}
                        },
                        {
                            field: 'location',
                            title: __('地区'),
                            visible: false,
                            operate: false,
                            sortable: false
                        },
                        {
                            field: 'batch',
                            title: __('批次'),
                            visible: true,
                            operate: '=',
                            searchList: {"本科": __('本科'), "专科": __('专科')}
                        },

                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }


                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
            var url = '';
            //当为新选项卡中打开时
            if (Config.cms.archiveseditmode == 'addtabs') {
                url = (url + '?ids=' + $(".commonsearch-table input[name=channel_id]").val());
            }
            $(".btn-add").off("click").on("click", function () {
                var url = 'cms/archives/add?channel=' + $(".commonsearch-table input[name=channel_id]").val();
                //当为新选项卡中打开时
                if (Config.cms.archiveseditmode == 'addtabs') {
                    Fast.api.addtabs(url, __('Add'));
                } else {
                    Fast.api.open(url, __('Add'), $(this).data() || {});
                }
                return false;
            });

            $(document).on("click", "a.btn-channel", function () {
                $("#archivespanel").toggleClass("col-md-9", $("#channelbar").hasClass("hidden"));
                $("#channelbar").toggleClass("hidden");
            });

            $(document).on("click", "a.btn-setspecial", function () {
                var ids = Table.api.selectedids(table);
                Layer.open({
                    title: __('Set special'),
                    content: Template("specialtpl", {}),
                    btn: [__('Ok')],
                    yes: function (index, layero) {
                        var special_id = $("select[name='special']", layero).val();
                        if (special_id == 0) {
                            Toastr.error(__('Please select special'));
                            return;
                        }
                        Fast.api.ajax({
                            url: "cms/archives/special/ids/" + ids.join(","),
                            type: "post",
                            data: {special_id: special_id},
                        }, function () {
                            table.bootstrapTable('refresh', {});
                            Layer.close(index);
                        });
                    },
                    success: function (layero, index) {
                    }
                });
            });

            $(document).on("click", "a.btn-province", function () {
                var ids = Table.api.selectedids(table);
                Layer.open({
                    title: __('省份修改'),
                    content: Template("province", {}),
                    btn: [__('Ok')],
                    yes: function (index, layero) {
                        var special_id = $("select[name='province']", layero).val();
                        if (special_id == 0) {
                            Toastr.error(__('请选择'));
                            return;
                        }
                        Fast.api.ajax({
                            url: "cms/archives/province/ids/" + ids.join(","),
                            type: "post",
                            data: {province: special_id},
                        }, function () {
                            table.bootstrapTable('refresh', {});
                            Layer.close(index);
                        });
                    },
                    success: function (layero, index) {
                    }
                });
            });

            require(['jstree'], function () {
                //全选和展开
                $(document).on("click", "#checkall", function () {
                    $("#channeltree").jstree($(this).prop("checked") ? "check_all" : "uncheck_all");
                });
                $(document).on("click", "#expandall", function () {
                    $("#channeltree").jstree($(this).prop("checked") ? "open_all" : "close_all");
                });
                $('#channeltree').on("changed.jstree", function (e, data) {
                    $(".commonsearch-table input[name=channel_id]").val(data.selected.join(","));
                    table.bootstrapTable('refresh', {});
                    return false;
                });
                $('#channeltree').jstree({
                    "themes": {
                        "stripes": true
                    },
                    "checkbox": {
                        "keep_selected_style": false,
                    },
                    "types": {
                        "channel": {
                            "icon": "fa fa-th",
                        },
                        "list": {
                            "icon": "fa fa-list",
                        },
                        "link": {
                            "icon": "fa fa-link",
                        },
                        "disabled": {
                            "check_node": false,
                            "uncheck_node": false
                        }
                    },
                    'plugins': ["types", "checkbox"],
                    "core": {
                        "multiple": true,
                        'check_callback': true,
                        "data": Config.channelList
                    }
                });
            });

            $(document).on('click', '.btn-move', function () {
                var ids = Table.api.selectedids(table);
                Layer.open({
                    title: __('Move'),
                    content: Template("channeltpl", {}),
                    btn: [__('Move')],
                    yes: function (index, layero) {
                        var channel_id = $("select[name='channel']", layero).val();
                        if (channel_id == 0) {
                            Toastr.error(__('Please select channel'));
                            return;
                        }
                        Fast.api.ajax({
                            url: "cms/archives/move/ids/" + ids.join(","),
                            type: "post",
                            data: {channel_id: channel_id},
                        }, function () {
                            table.bootstrapTable('refresh', {});
                            Layer.close(index);
                        });
                    },
                    success: function (layero, index) {
                    }
                });
            });
        },
        content: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'cms/archives/content/model_id/' + Config.model_id,
                    add_url: '',
                    edit_url: 'cms/archives/edit',
                    del_url: 'cms/archives/del',
                    multi_url: '',
                    table: '',
                }
            });

            var table = $("#table");
            //在表格内容渲染完成后回调的事件
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                //当为新选项卡中打开时
                if (Config.cms.archiveseditmode == 'addtabs') {
                    $(".btn-editone", this)
                        .off("click")
                        .removeClass("btn-editone")
                        .addClass("btn-addtabs")
                        .prop("title", __('Edit'));
                }
            });
            //默认字段
            var columns = [
                {checkbox: true},
                //这里因为涉及到关联多个表,因为用了两个字段来操作,一个隐藏,一个搜索
                {field: 'main.id', title: __('Id'), visible: false},
                {field: 'id', title: __('Id'), operate: false},
                {field: 'title', title: __('Title'), operate: 'like'},
                {
                    field: 'channel_id',
                    title: __('Channel_id'),
                    addclass: 'selectpage',
                    extend: 'data-source="cms/channel/index"',
                    formatter: Table.api.formatter.search
                },
                {field: 'channel_name', title: __('Channel_name'), operate: false}
            ];
            //动态追加字段

            $.each(Config.fields, function (i, j) {
                console.log(j)
                var data = {field: j.field, title: j.title, table: table, operate: (j.type === 'number' ? '=' : 'like')};
                //如果是图片,加上formatter
                if (j.type == 'image') {
                    data.events = Table.api.events.image;
                    data.formatter = Table.api.formatter.image;
                } else if (j.type == 'images') {
                    data.events = Table.api.events.image;
                    data.formatter = Table.api.formatter.images;
                } else if (j.type == 'radio' || j.type == 'checkbox' || j.type == 'select' || j.type == 'selects') {
                    data.formatter = Controller.api.formatter.content;
                    data.extend = j.content;
                    data.searchList = j.content;
                } else {
                    data.formatter = Table.api.formatter.content;
                }
                columns.push(data);
            });
            //追加操作字段
            columns.push({
                field: 'operate',
                title: __('Operate'),
                table: table,
                width: '100px',
                events: Table.api.events.operate,
                formatter: Table.api.formatter.operate
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: columns
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        diyform: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'cms/archives/diyform/diyform_id/' + Config.diyform_id,
                    add_url: '',
                    edit_url: 'cms/archives/edit',
                    del_url: 'cms/archives/del',
                    multi_url: '',
                    table: '',
                }
            });

            var table = $("#table");
            //在表格内容渲染完成后回调的事件
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-editone", this)
                    .off("click")
                    .removeClass("btn-editone")
                    .addClass("btn-addtabs")
                    .prop("title", __('Edit'));
            });
            //默认字段
            var columns = [
                {checkbox: true},
                {field: 'id', title: __('Id'), operate: false},
            ];
            //动态追加字段
            $.each(Config.fields, function (i, j) {
                var data = {field: j.field, title: j.title, operate: 'like'};
                //如果是图片,加上formatter
                if (j.type == 'image') {
                    data.formatter = Table.api.formatter.image;
                } else if (j.type == 'images') {
                    data.formatter = Table.api.formatter.images;
                } else if (j.type == 'radio' || j.type == 'check' || j.type == 'select' || j.type == 'selects') {
                    data.formatter = Controller.api.formatter.content;
                    data.extend = j.content;
                } else {
                    data.formatter = Table.api.formatter.content;
                }
                columns.push(data);
            });
            //追加操作字段
            columns.push({
                field: 'operate',
                title: __('Operate'),
                table: table,
                events: Table.api.events.operate,
                formatter: Table.api.formatter.operate
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: columns
            })
            ;

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'cms/archives/recyclebin',
                pk: 'id',
                sortName: 'weigh',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'title', title: __('Title'), align: 'left'},
                        {field: 'image', title: __('Image'), operate: false, formatter: Table.api.formatter.image},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'cms/archives/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'cms/archives/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            // var last_channel_id = localStorage.getItem('last_channel_id');
            var last_channel_id;
            var channel = Fast.api.query("channel");
            if (channel) {
                var channelIds = channel.split(",");
                $(channelIds).each(function (i, j) {
                    if ($("#c-channel_id option[value='" + j + "']:disabled").size() > 0) {
                        return true;
                    }
                    last_channel_id = j;
                    return false;
                });
            }
            if (last_channel_id) {
                $("#c-channel_id option[value='" + last_channel_id + "']").prop("selected", true);
            }
            Controller.api.bindevent();
            $("#c-channel_id").trigger("change");

            // $('#full0').click(function(){
            //     $(this).val(0);
            //      $(this).attr('checked',true);
            //     $('#full1').val(1);
            //     $('#full1').attr('checked',false);
            //     // var checkValue = $('input:radio[name="pathType"]:checked').val();
            // });
            //
            // $('#full1').click(function(){
            //     $(this).val(1);
            //     $(this).attr('checked',true);
            //     $('#full0').val(0);
            //     $('#full0').attr('checked',false);
            //     // var checkValue = $('input:radio[name="pathType"]:checked').val();
            // });


        },
        add_new: function () {
            // var last_channel_id = localStorage.getItem('last_channel_id');
            var last_channel_id;
            var channel = Fast.api.query("channel");
            if (channel) {
                var channelIds = channel.split(",");
                $(channelIds).each(function (i, j) {
                    if ($("#c-channel_id1 option[value='" + j + "']:disabled").size() > 0) {
                        return true;
                    }
                    last_channel_id = j;
                    return false;
                });
            }
            if (last_channel_id) {
                $("#c-channel_id1 option[value='" + last_channel_id + "']").prop("selected", true);
            }
            Controller.api.bindevent();
            $("#c-channel_id1").trigger("change");

            // $('#full0').click(function(){
            //     $(this).val(0);
            //      $(this).attr('checked',true);
            //     $('#full1').val(1);
            //     $('#full1').attr('checked',false);
            //     // var checkValue = $('input:radio[name="pathType"]:checked').val();
            // });
            //
            // $('#full1').click(function(){
            //     $(this).val(1);
            //     $(this).attr('checked',true);
            //     $('#full0').val(0);
            //     $('#full0').attr('checked',false);
            //     // var checkValue = $('input:radio[name="pathType"]:checked').val();
            // });


        },
        edit: function () {
            Controller.api.bindevent();
            $("#c-channel_id").trigger("change");
            // console.log($("#row[province][]-1").val());

        },
        preview:function(){
            var content =parent.$('#c-content').val();
            content=content.replace(/text-indent|&nbsp;|margin|margin-left|margin-right|margin|padding-left|padding-right|padding|font-family|line-height|font-size|width|height/g,'');
            $("#content2").html(content);
            // $("table").css("width",'unset !important');
            // $("p").css("font-size",'15px !important');
            // $("span").css("font-size",'15px !important');
            // $("h1").css("font-size",'16px !important');
        },
        test_bank: function () {
            $(".btn-add").data("area",["100%","100%"]);
            $(".btn-edit").data("area",["100%","100%"]);
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'cms/archives/test_bank'+ location.search,
                    add_url: 'cms/archives/add',
                    edit_url: 'cms/archives/edit?h_type=1',
                    del_url: 'cms/archives/del',
                    multi_url: 'cms/archives/multi',
                    dragsort_url: '',
                    table: 'cms_archives',
                }
            });

            var table = $("#table");

            //在表格内容渲染完成后回调的事件
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-editone").data("area",["100%","100%"]);
                //当为新选项卡中打开时
                if (Config.cms.archiveseditmode == 'addtabs') {
                    $(".btn-editone", this)
                        .off("click")
                        .removeClass("btn-editone")
                        .addClass("btn-addtabs")
                        .prop("title", __('Edit'));
                }
            });
            //当双击单元格时
            table.on('dbl-click-row.bs.table', function (e, row, element, field) {
                $(".btn-addtabs", element).trigger("click");
            });
            var content={1: "全国", 2: "北京", 3: "福建", 4: "浙江", 5: "河南", 6: "安徽", 7: "上海", 8: "江苏", 9: "山东", 10: "江西", 11: "重庆", 12: "湖南", 13: "湖北", 14: "广东", 15: "广西", 16: "贵州", 17: "海南", 18: "四川", 19: "云南", 20: "陕西", 21: "甘肃", 22: "宁夏", 23: "青海", 24: "新疆", 25: "西藏", 26: "天津", 27: "黑龙江", 28: "吉林", 29: "辽宁", 30: "河北", 31: "山西", 32: "内蒙古"};
            // 初始化表格
            var channels={182:'省市质检',181:'高考真题',180:'名校试卷',179:'学考试卷',177:'其他',178:'联考试卷'};

            // var test_type={1:'省市质检',2:'高考真题',3:'名校试卷',4:'学考试卷',5:'其他',6:'联考试卷',11:'联考试卷'};
            var subject={1:'语文',2:'数学',3:'英语',4:'物理',5:'化学',6:'生物',7:'地理',8:'政治',9:'历史',10:'信息技术',11:'文数',12:'理数',13:'文综',14:'理综',15:'其他'};
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'a.weigh DESC,a.publishtime DESC',
                pageSize:15,
                searchFormVisible: true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), sortable: true},
                        {
                            field: 'admin_id',
                            title: __('Admin_id'),
                            visible: false,
                            addclass: 'selectpage',
                            extend: 'data-source="auth/admin/selectpage?flag=1" data-field="nickname"',
                            operate: '=',
                            formatter: Table.api.formatter.search
                        },
                        {field: 'title', title: __('标题'),operate: 'like', formatter: function (value, row, index) {
                                if (value){
                                    return '<div class="archives-title"><a href="http://admin.gkzzd.cn/cms/a/'+row.id+'.html"  " target="_blank">'+row.title+'</a></div>' ;
                                }else {
                                    return '-';
                                }
                            }
                        },
                        {field: 'name',operate:false, title: __('栏目')},
                        {field: 'channel_id', visible: false,title: __('栏目'),searchList:channels},
                        {
                            field: 'province',
                            title: __('省份'),
                            // addclass: 'selectpage',
                            operate: 'find_in_set',
                            formatter : Table.api.formatter.label,
                            extend : content,
                            searchList : content,
                        },
                        {field: 'full',searchList:{"0": '更新中','1':'已完结'}, title: __('试卷状态'),formatter: function (value, row, index){
                                if (value=='1'){
                                    return '已完结';
                                }else if (value=='0'){
                                    return '更新中';
                                }else if (value=='2'){
                                    return '仅试卷';
                                }else if (value=='3'){
                                    return '仅答案';
                                }else {
                                    return '-';
                                }
                            }},
                        {field: 'test_grade',operate:false, title: __('年级'),formatter: function (value, row, index){
                                if (value=='1'){
                                    return '高一';
                                }else if (value=='2'){
                                    return '高二';
                                }else if (value=='3'){
                                    return '高三';
                                }else {
                                    return '-';
                                }
                            }},
                        // {field: 'test_type', formatter : Controller.api.formatter.content,
                        //     extend : test_type,
                        //     searchList : test_type, title: __('类型')},
                        {field: 'paper_subject_id', formatter : Controller.api.formatter.content,
                            extend : subject,
                            searchList : subject, title: __('学科')},
                        {field: 'year', title: __('年份'), operate: false, },

                        {field: 'flag', title: __('Flag'), operate: '=', visible: false, searchList: Config.flagList, formatter: Table.api.formatter.flag},
                        {field: 'source', title: __('来源'),visible: false, operate: false, sortable: false},
                        {
                            field: 'createtime',
                            title: __('Createtime'),
                            visible: false,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime,
                            autocomplete: false
                        },
                        {
                            field: 'updatetime',
                            title: __('Updatetime'),
                            visible: false,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime,
                            autocomplete: false
                        },
                        {
                            field: 'publishtime',
                            title: __('Publishtime'),
                            sortable: true,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime,
                            datetimeFormat: "YYYY-MM-DD",
                            autocomplete: false
                        },
                        {field: 'status', title: __('Status'), searchList: {"normal": __('Status normal'), "hidden": __('Status hidden'), "rejected": __('Status rejected'), "pulloff": __('Status pulloff')}, formatter: Table.api.formatter.status},
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }


                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            var url = '';
            //当为新选项卡中打开时
            if (Config.cms.archiveseditmode == 'addtabs') {
                url = (url + '?ids=' + $(".commonsearch-table input[name=channel_id]").val());
            }

            $(".btn-add1").off("click").on("click", function () {
                var url = 'cms/archives/add?list_type=5&h_type=1';
                //当为新选项卡中打开时
                if (Config.cms.archiveseditmode == 'addtabs') {
                    Fast.api.addtabs(url, __('添加试卷'));
                } else {
                    Fast.api.open(url, __('添加试卷'), $(this).data() || {});
                }
                return false;
            });

            $(document).on("click", ".btn-add2", function () {
                Fast.api.open('cms.special/add?h_type=1', __('添加试卷专题'),{area:['80%', '80%']}, {
                    callback:function(value){

                    }
                });
            });

            $(document).on("click", "a.btn-channel", function () {
                $("#archivespanel").toggleClass("col-md-9", $("#channelbar").hasClass("hidden"));
                $("#channelbar").toggleClass("hidden");
            });

            $(document).on("click", "a.btn-setspecial", function () {
                var ids = Table.api.selectedids(table);
                Layer.open({
                    title: __('Set special'),
                    content: Template("specialtpl", {}),
                    btn: [__('Ok')],
                    yes: function (index, layero) {
                        var special_id = $("select[name='special']", layero).val();
                        if (special_id == 0) {
                            Toastr.error(__('Please select special'));
                            return;
                        }
                        Fast.api.ajax({
                            url: "cms/archives/special/ids/" + ids.join(","),
                            type: "post",
                            data: {special_id: special_id},
                        }, function () {
                            table.bootstrapTable('refresh', {});
                            Layer.close(index);
                        });
                    },
                    success: function (layero, index) {
                    }
                });
            });

            require(['jstree'], function () {
                //全选和展开
                $(document).on("click", "#checkall", function () {
                    $("#channeltree").jstree($(this).prop("checked") ? "check_all" : "uncheck_all");
                });
                $(document).on("click", "#expandall", function () {
                    $("#channeltree").jstree($(this).prop("checked") ? "open_all" : "close_all");
                });
                $('#channeltree').on("changed.jstree", function (e, data) {
                    $(".commonsearch-table input[name=channel_id]").val(data.selected.join(","));
                    table.bootstrapTable('refresh', {});
                    return false;
                });
                $('#channeltree').jstree({
                    "themes": {
                        "stripes": true
                    },
                    "checkbox": {
                        "keep_selected_style": false,
                    },
                    "types": {
                        "channel": {
                            "icon": "fa fa-th",
                        },
                        "list": {
                            "icon": "fa fa-list",
                        },
                        "link": {
                            "icon": "fa fa-link",
                        },
                        "disabled": {
                            "check_node": false,
                            "uncheck_node": false
                        }
                    },
                    'plugins': ["types", "checkbox"],
                    "core": {
                        "multiple": true,
                        'check_callback': true,
                        "data": Config.channelList
                    }
                });
            });

            $(document).on('click', '.btn-move', function () {
                var ids = Table.api.selectedids(table);
                Layer.open({
                    title: __('Move'),
                    content: Template("channeltpl", {}),
                    btn: [__('Move')],
                    yes: function (index, layero) {
                        var channel_id = $("select[name='channel']", layero).val();
                        if (channel_id == 0) {
                            Toastr.error(__('Please select channel'));
                            return;
                        }
                        Fast.api.ajax({
                            url: "cms/archives/move/ids/" + ids.join(","),
                            type: "post",
                            data: {channel_id: channel_id},
                        }, function () {
                            table.bootstrapTable('refresh', {});
                            Layer.close(index);
                        });
                    },
                    success: function (layero, index) {
                    }
                });
            });
        },
        api: {
            formatter: {
                content: function (value, row, index) {
                    var extend = this.extend;
                    if (!value) {
                        return '';
                    }
                    var valueArr = value.toString().split(/,/);
                    var result = [];
                    $.each(valueArr, function (i, j) {
                        result.push(typeof extend[j] !== 'undefined' ? extend[j] : j);
                    });
                    return result.join(',');
                }
            },
            bindevent: function () {
                var refreshStyle = function () {
                    var style = [];
                    if ($(".btn-bold").hasClass("active")) {
                        style.push("b");
                    }
                    if ($(".btn-color").hasClass("active")) {
                        style.push($(".btn-color").data("color"));
                    }
                    $("input[name='row[style]']").val(style.join("|"));
                };
                var insertHtml = function (html) {
                    if (typeof KindEditor !== 'undefined') {
                        KindEditor.insertHtml("#c-content", html);
                    } else if (typeof UM !== 'undefined' && typeof UM.list["c-content"] !== 'undefined') {
                        UM.list["c-content"].execCommand("insertHtml", html);
                    } else if (typeof UE !== 'undefined' && typeof UE.list["c-content"] !== 'undefined') {
                        UE.list["c-content"].execCommand("insertHtml", html);
                    } else if ($("#c-content").data("summernote")) {
                        $('#c-content').summernote('pasteHTML', html);
                    } else if (typeof Simditor !== 'undefined' && typeof Simditor.list['c-content'] !== 'undefined') {
                        Simditor.list['c-content'].setValue($('#c-content').val() + html);
                    } else {
                        Layer.open({
                            content: "你的编辑器暂不支持插入HTML代码，请手动复制以下代码到你的编辑器" + "<textarea class='form-control' rows='5'>" + html + "</textarea>", title: "温馨提示"
                        });
                    }
                };
                $(document).on("click", ".btn-paytag", function () {
                    insertHtml("##paidbegin##\n\n请替换付费标签内内容\n\n##paidend##");
                });
                $(document).on("click", ".btn-pagertag", function () {
                    insertHtml("##pagebreak##");
                });
                // $(".checkbox-inline input").eq(1).attr("disabled","disabled");
                $(document).on("click", "#extend .checkbox-inline input", function () {
                    var that=$(this);
                    if (that.eq(0).val()==1){
                        if (that.eq(0).is(':checked')==true){
                            that.parent().parent().siblings().find('input').attr("disabled","disabled");
                            // that.parent().parent().siblings().find('input').checked=false;
                            that.parent().parent().siblings().find('input').prop('checked',false);
                        }else {
                            that.parent().parent().siblings().find('input').removeAttr("disabled");
                        }
                    }else {

                    }
                });
                require(['jquery-colorpicker'], function () {
                    $('.colorpicker').colorpicker({
                        color: function () {
                            var color = "#000000";
                            var rgb = $("#c-title").css('color').match(/^rgb\(((\d+),\s*(\d+),\s*(\d+))\)$/);
                            if (rgb) {
                                color = rgb[1];
                            }
                            return color;
                        }
                    }, function (event, obj) {
                        $("#c-title").css('color', '#' + obj.hex);
                        $(event).addClass("active").data("color", '#' + obj.hex);
                        refreshStyle();
                    }, function (event) {
                        $("#c-title").css('color', 'inherit');
                        $(event).removeClass("active");
                        refreshStyle();
                    });
                });
                // require(['jquery-tagsinput'], function () {
                //     //标签输入
                //     var elem = "#c-tags";
                //     var tags = $(elem);
                //     tags.tagsInput({
                //         width: 'auto',
                //         defaultText: '输入后空格确认',
                //         minInputWidth: 110,
                //         height: '36px',
                //         placeholderColor: '#999',
                //         onChange: function (row) {
                //             if (typeof callback === 'function') {
                //
                //             } else {
                //                 $(elem + "_addTag").focus();
                //                 $(elem + "_tag").trigger("blur.autocomplete").focus();
                //             }
                //         },
                //         autocomplete: {
                //             url: 'cms/tag/autocomplete',
                //             minChars: 1,
                //             menuClass: 'autocomplete-tags'
                //         }
                //     });
                // });
                //获取标题拼音

                $(document).on("click", "#all_check", function () {
                    var flag =$(this).attr('val');
                    if (flag=='1'){
                        $("input[name='row[province][]']").prop('checked',true);
                        $(this).attr('val','2');
                    }else {
                        $("input[name='row[province][]']").prop('checked',false);
                        $(this).attr('val','1');
                    }
                });
                var si;
                $(document).on("keyup", "#c-title", function () {
                    var value = $(this).val();
                    if (value != '' && !value.match(/\n/)) {
                        clearTimeout(si);
                        si = setTimeout(function () {
                            Fast.api.ajax({
                                loading: false,
                                url: "cms/ajax/get_title_pinyin",
                                data: {title: value, delimiter: "-"}
                            }, function (data, ret) {
                                $("#c-diyname").val(data.pinyin.substr(0, 255));
                                return false;
                            }, function (data, ret) {
                                return false;
                            });
                        }, 200);
                    }
                });
                $(document).on('click', '.btn-bold', function () {
                    $("#c-title").toggleClass("text-bold", !$(this).hasClass("active"));
                    $(this).toggleClass("text-bold active");
                    refreshStyle();
                });
                $(document).on('change', '#c-channel_id', function () {
                    var model = $("option:selected", this).attr("model");
                    var value = $(this).val();
                    // var s_flag=$("#s_flag").val();
                    Fast.api.ajax({
                        url: 'cms/archives/get_fields_html',
                        data: {policy_type:$("#policy_type").val(),channel_id: value, archives_id: $("#archive-id").val(),pro_id: $("#pro").val()}
                    }, function (data) {
                        if ($("#extend").data("model") != model) {
                            $("#extend").html(data.html).data("model", model);
                            Form.api.bindevent($("#extend"));
                        }
                        return false;
                    });
                    localStorage.setItem('last_channel_id', $(this).val());
                    $("#c-channel_ids option").prop("disabled", true);
                    $("#c-channel_ids option[model!='" + model + "']").prop("selected", false);
                    $("#first").prop("disabled", false);
                    $("#c-channel_id option[model='" + model + "']:not([disabled])").each(function () {
                        $("#c-channel_ids option[model='" + $(this).attr("model") + "'][value='" + $(this).attr("value") + "']").prop("disabled", false);
                    });
                    if ($("#c-channel_ids").data("selectpicker")) {
                        $("#c-channel_ids").data("selectpicker").refresh();
                    }
                    // if (value==45){
                    //     // $(".checkbox-inline").children().eq(1).prop('checked',false);
                    //     $("#year-2").prop("checked",false);
                    //     $("#year-3").prop("checked",true);
                    // }else if (value==26 || value==27 || value==28 || value==69){
                    //     $("#year-2").prop("checked",false);
                    //     $("#year-1").prop("checked",true);
                    // }
                });
                $(document).on('change', '#c-channel_id1', function () {
                    var model = $("option:selected", this).attr("model");
                    var value = $(this).val();
                    // var s_flag=$("#s_flag").val();
                    Fast.api.ajax({
                        url: 'cms/archives/get_fields_html',
                        data: {policy_type:$("#policy_type").val(),channel_id: value, archives_id: $("#archive-id").val(),pro_id: $("#pro").val()}
                    }, function (data) {
                        if ($("#extend").data("model") != model) {
                            $("#extend").html(data.html).data("model", model);
                            Form.api.bindevent($("#extend"));
                        }
                        return false;
                    });
                    localStorage.setItem('last_channel_id', $(this).val());
                    $("#c-channel_ids option").prop("disabled", true);
                    $("#c-channel_ids option[model!='" + model + "']").prop("selected", false);
                    $("#first").prop("disabled", false);
                    $("#c-channel_id1 option[model='" + model + "']:not([disabled])").each(function () {
                        $("#c-channel_ids option[model='" + $(this).attr("model") + "'][value='" + $(this).attr("value") + "']").prop("disabled", false);
                    });
                    if ($("#c-channel_ids").data("selectpicker")) {
                        $("#c-channel_ids").data("selectpicker").refresh();
                    }
                    // if (value==45){
                    //     // $(".checkbox-inline").children().eq(1).prop('checked',false);
                    //     $("#year-2").prop("checked",false);
                    //     $("#year-3").prop("checked",true);
                    // }else if (value==26 || value==27 || value==28 || value==69){
                    //     $("#year-2").prop("checked",false);
                    //     $("#year-1").prop("checked",true);
                    // }
                });
                $(document).on("fa.event.appendfieldlist", ".downloadlist", function (a) {
                    Form.events.plupload(this);
                    $(".fachoose", this).off("click");
                    Form.events.faselect(this);
                });
                //检测内容
                $(document).on("click", ".btn-legal", function (a) {
                    Fast.api.ajax({
                        url: "cms/ajax/check_content_islegal",
                        data: {content: $("#c-content").val()}
                    }, function (data, ret) {

                    }, function (data, ret) {
                        if ($.isArray(data)) {
                            if (data.length > 1) {
                                Layer.alert(__('Banned words') + "：" + data.join(","));
                            } else {
                                Layer.alert(ret.msg);
                            }
                            return false;
                        }
                    });
                });
                //提取关键字
                $(document).on("click", ".btn-keywords", function (a) {
                    Fast.api.ajax({
                        url: "cms/ajax/get_content_keywords",
                        data: {title: $("#c-title").val(), tags: $("#c-tags").val(), content: $("#c-content").val()}
                    }, function (data, ret) {
                        $("#c-keywords").val(data.keywords);
                        // $("#c-tags").val(data.keywords);
                        $("#c-description").val(data.description);
                    });
                });
                //提取缩略图
                $(document).on("click", ".btn-getimage", function (a) {
                    var image = $("<div>" + $("#c-content").val() + "</div>").find('img').first().attr('src');
                    if (image) {
                        var obj = $("#c-image");
                        if (obj.val() != '') {
                            Layer.confirm("缩略图已存在，是否替换？", {icon: 3}, function (index) {
                                obj.val(image).trigger("change");
                                layer.close(index);
                                Toastr.success("提取成功");
                            });
                        } else {
                            obj.val(image).trigger("change");
                            Toastr.success("提取成功");
                        }

                    } else {
                        Toastr.error("未找到任何图片");
                    }
                    return false;
                });
                //提取组图
                $(document).on("click", ".btn-getimages", function (a) {
                    var image = $("<div>" + $("#c-content").val() + "</div>").find('img').first().attr('src');
                    if (image) {
                        var imageArr = [];
                        $("<div>" + $("#c-content").val() + "</div>").find('img').each(function (i, j) {
                            if (i > 3) {
                                return false;
                            }
                            imageArr.push($(this).attr("src"));
                        });
                        image = imageArr.slice(0, 4).join(",");
                        var obj = $("#c-images");
                        if (obj.val() != '') {
                            Layer.confirm("文章组图已存在，是否替换？", {icon: 3}, function (index) {
                                obj.val(image).trigger("change");
                                layer.close(index);
                                Toastr.success("提取成功");
                            });
                        } else {
                            obj.val(image).trigger("change");
                            Toastr.success("提取成功");
                        }

                    } else {
                        Toastr.error("未找到任何图片");
                    }
                    return false;
                });



                $('.btn-embossed').tooltip({
                    title: '请先预览',
                    html: true,
                    container: 'body',
                });
                $(document).on("click", ".btn-preview", function (a) { //预览
                    var title=$("#c-title").val();
                    var content=$("#c-content").val();
                    var channel_id=$("#c-channel_id").val();
                    // if (channel_id==39 || channel_id==70){
                    //     var channel_ids=$("#c-channel_ids").val();
                    //     if (channel_ids==''){
                    //         layer.msg('请选择副栏目');
                    //         return false;
                    //     }
                    // }
                    var school_id=$("#school_id").val();
                    var a_id=$("#archive-id").val();
                    if (title=='' || content=='' ||channel_id ==''){
                        layer.msg('请填写栏目,文章标题与内容');
                        return false;
                    }
                    // var id=$("#archive-id").val();
                    var h_type=$("#h_type").val();
                    var source=$("#c-source").val();
                    var keywords=$("#c-keywords").val();
                    if (keywords==''){
                        layer.msg('请先获取关键词');
                        return false;
                    }
                    if (source==''){
                        layer.msg('请先填写来源');
                        return false;
                    }
                    if (h_type==1){
                        if(content.indexOf("#gkzzd") == -1 ) {
                            layer.msg('试卷内容请加#gkzzd#,加完后再预览');
                            return false;
                        }
                        var description=$("#c-description").val();
                        if (description=='' || description=='#gkzzd#'){
                            layer.msg('请在正文头部添加介绍');
                            return false;
                        }
                    }
                    // if (!id){
                        Fast.api.ajax({
                            url: 'cms/archives/repetition',
                            data: {title: title,channel_id:channel_id,school_id:school_id,a_id:a_id}
                        }, function (data) {
                            $(".btn-embossed").attr('disabled',false);
                            var arr=[title,content];
                            // console.log(content)
                            // arr=JSON.parse(arr);
                            var url = "cms/archives/preview?title="+title;//弹出窗口 add.html页面的（fastadmin封装layer模态框将以iframe的方式将add输出到index页面的模态框里）
                            Fast.api.open(url, __('预览'), {
                                callback:function(value){

                                }
                            });
                        });
                    // }

                });

                $.validator.config({
                    rules: {
                        diyname: function (element) {
                            if (element.value.toString().match(/^\d+$/)) {
                                return __('Can not be only digital');
                            }
                            if (!element.value.toString().match(/^[a-zA-Z0-9\-_]+$/)) {
                                return __('Please input character or digital');
                            }
                            return $.ajax({
                                url: 'cms/archives/check_element_available',
                                type: 'POST',
                                data: {id: $("#archive-id").val(), name: element.name, value: element.value},
                                dataType: 'json'
                            });
                        },
                        isnormal: function (element) {
                            return $("#c-status").val() == 'normal' ? true : false;
                        }
                    }
                });
                var iscontinue = false;
                $(document).on("click", ".btn-continue", function () {
                    iscontinue = true;
                    $(this).prev().trigger("click");
                });
                Form.api.bindevent($("form[role=form]"), function () {
                    if (iscontinue) {
                        $(window).scrollTop(0);
                        location.reload();
                        top.window.Toastr.success(__('Operation completed'));
                        return false;
                    } else {
                        if ($("#h_type").val()=='1'){

                        }else {
                            if ($("#flag_channel").val()!='')
                            {
                                var obj = top.window.$("ul.nav-addtabs li.active");
                                top.window.Toastr.success(__('Operation completed'));
                                // top.window.$(".sidebar-menu a[url$='/cms/archives'][addtabs]").click();
                                // top.window.$(".sidebar-menu a[url$='/cms/archives'][addtabs]").dblclick();
                                obj.find(".fa-remove").trigger("click");
                                // window.history.back();
                            }else {
                                if ($("#s_flag").val()!=''){
                                    // parent.location.reload();
                                }else {
                                    if (Config.cms.archiveseditmode == 'addtabs') {
                                        var obj = top.window.$("ul.nav-addtabs li.active");
                                        top.window.Toastr.success(__('Operation completed'));
                                        top.window.$(".sidebar-menu a[url$='/cms/archives'][addtabs]").click();
                                        top.window.$(".sidebar-menu a[url$='/cms/archives'][addtabs]").dblclick();
                                        obj.find(".fa-remove").trigger("click");
                                    }
                                }
                            }
                        }
                    }

                });
            }
        }
    };
    return Controller;
});